package com.longcai.controller.goods;


import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.zxing.WriterException;
import com.longcai.bean.PageHelper;
import com.longcai.entity.homegood.ClyjGoodsHomepage;
import com.longcai.entity.homegood.ClyjGoodsPics;
import com.longcai.entity.homegood.ClyjGoodsSpec;
import com.longcai.entity.homegood.ClyjGoodsVo;
import com.longcai.entity.homepage.ClyjSeckillGoods;
import com.longcai.entity.sys.SysRoleUser;
import com.longcai.entity.sys.SysUser;
import com.longcai.page.table.PageTableResponse;
import com.longcai.service.goods.ClyjGoodsHomepageService;
import com.longcai.service.goods.ClyjSeckillGoodsService;
import com.longcai.util.LoginUser;
import com.longcai.util.OSSUtils;
import com.longcai.util.QRCodeUtils;
import com.longcai.util.UUIDUtil;
import com.longcai.util.UserUtil;

import io.swagger.annotations.ApiOperation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;

/**
 * <p>
 * 秒杀商品 前端控制器
 * </p>
 *
 * @author LWK
 * @since 2019-04-08
 */
@Controller
@RequestMapping("/clyjSeckillGoods")
public class ClyjSeckillGoodsController {
	private Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    private ClyjSeckillGoodsService skillService;
    @Autowired
    private ClyjGoodsHomepageService clyjGoodsHomepageService;
    
    /**
     * 分页查询秒杀商品
     *
     * @return
     */
    @GetMapping(value = "getSkillGoods")
    @ResponseBody
    public PageTableResponse getGoods(ClyjSeckillGoods skillGoods, PageHelper pageHelper) {
    	Page<ClyjSeckillGoods> page =new Page<ClyjSeckillGoods>(pageHelper.getStart(),pageHelper.getLength());
    	QueryWrapper<ClyjGoodsHomepage> w = new QueryWrapper<ClyjGoodsHomepage>();
    	if(skillGoods.getGoodsName()!=null && skillGoods.getGoodsName()!="")
    		w.like("goods_name", skillGoods.getGoodsName());
    	//获取当前用户信息
    	LoginUser loginUser = UserUtil.getLoginUser();
    	if(loginUser.getId()!=1)
    		w.eq("supplier_id", loginUser.getId());
    	w.orderByDesc("month_sales");
    	//查询出商品列表
    	try{
	    	List<ClyjGoodsHomepage> selectList = clyjGoodsHomepageService.selectList(w);
	    	//获取id集合
	    	QueryWrapper<ClyjSeckillGoods> w2 = new QueryWrapper<ClyjSeckillGoods>();
	    	List<String> list = new ArrayList<String>();
	    	Map<String,String> map = new HashMap<String,String>();
	    	for (ClyjGoodsHomepage clyjGoodsHomepage : selectList) {
	    		list.add(clyjGoodsHomepage.getGoodsId());
	    		map.put(clyjGoodsHomepage.getGoodsId(),clyjGoodsHomepage.getGoodsName()+","+clyjGoodsHomepage.getOriginalPrice());
			}
	    	w2.in("goods_id",list);
	        IPage<ClyjSeckillGoods> sysRoleIPage = skillService.selectPage(page, w2);
	        List<ClyjSeckillGoods> records = sysRoleIPage.getRecords();
	        for (ClyjSeckillGoods string : records) {
	        	string.setOriginalPrice(map.get(string.getGoodsId()).split(",")[1]);
	        	string.setGoodsName(map.get(string.getGoodsId()).split(",")[0]);
			}
	        sysRoleIPage.setRecords(records);
	        PageTableResponse pageTableResponse = new PageTableResponse(sysRoleIPage.getTotal(),
	                sysRoleIPage.getTotal(), sysRoleIPage.getRecords());
	        return pageTableResponse;
        }catch(Exception e){
        	e.printStackTrace();
        }
        
        return null;
    }
    
    /**
     * 查询所有商品
     *
     * @return
     */
    @GetMapping(value = "getGoods")
    @ResponseBody
    public List<ClyjGoodsHomepage> getGoods(ClyjSeckillGoods sysRole) {
    	QueryWrapper<ClyjGoodsHomepage> w = new QueryWrapper<ClyjGoodsHomepage>();
    	//获取当前用户信息
    	LoginUser loginUser = UserUtil.getLoginUser();
    	if(loginUser.getId()!=1)
    		w.eq("supplier_id", loginUser.getId());
    	w.orderByDesc("month_sales");
    	QueryWrapper<ClyjSeckillGoods> queryWrapper = new QueryWrapper<ClyjSeckillGoods>();
    	queryWrapper.ne("id",sysRole.getId());
    	List<ClyjSeckillGoods> selectList = skillService.selectList(queryWrapper);
    	List<String> list = new ArrayList<String>();
        for (ClyjSeckillGoods string : selectList) {
        	list.add(string.getGoodsId());
		}
        w.notIn("goods_id", list);
    	List<ClyjGoodsHomepage> sysRoleIPage = clyjGoodsHomepageService.selectList( w);
        return sysRoleIPage;
    }
    
    /**
     * 新增商品
     *
     * @param goodsClas2s
     * @return
     */
    @PostMapping(value = "saveGoods")
    @ResponseBody
    public boolean save(ClyjSeckillGoods goodsClas2s) throws IOException, WriterException {
        if (goodsClas2s.getId() == null || goodsClas2s.getId() == "" || goodsClas2s.getId().equals("")) {
            //新增
        	goodsClas2s.setId(UUIDUtil.uuid());
            goodsClas2s.setCreateTime(LocalDateTime.now());
            goodsClas2s.setStatus(0);
            this.skillService.insert(goodsClas2s);


        } else {
            goodsClas2s.setUpdateTime(LocalDateTime.now());
            this.skillService.updateById(goodsClas2s);
        }
        return true;
    }


    /**
     * 根据id获取秒杀商品
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
    @ApiOperation(value = "根据id获取商品")
    @ResponseBody
    public ClyjSeckillGoods get(@PathVariable String id) {
        ClyjSeckillGoods selectById = skillService.selectById(id);
        return selectById;
    }
    
    @DeleteMapping("{id}")
    @ApiOperation(value = "删除秒杀商品")
    @ResponseBody
    @PreAuthorize("hasAuthority('goods:skill:del')")
    public void delete(@PathVariable String id) {
        this.skillService.deleteById(id);
    }
}

